/* eslint-disable no-use-before-define */
/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { computed, defineComponent, SetupContext, ref, onMounted, onBeforeMount, onUnmounted } from 'vue';
import { LoadingProps, loadingProps } from './loading.props';
import { Subject, BehaviorSubject } from 'rxjs';
import { LOADING_STYLES } from './composition/types';
import { filter, takeUntil } from 'rxjs/operators';

import './loading.css';

export default defineComponent({
    name: 'FLoading',
    props: loadingProps,
    emits: ['closed'] as (string[] & ThisType<void>) | undefined,
    setup(props: LoadingProps, context: SetupContext) {
        const loadingStyleDom = LOADING_STYLES;
        const isActive = ref(true);
        // const activeSubject = new BehaviorSubject(false);
        const width = 30;
        /** loading 样式 */
        const type = 0;
        // const delay = 300;
        // let activedSubscrition = null;
        let parentContainer: any;
        // const destroy$ = new Subject();
        const loadingBackdrop = ref<HTMLDivElement | null>(null);
        const loadingContainerEl = ref<HTMLDivElement | null>(null);
        // const isActive = computed({
        //     get() {
        //         return _isActive;
        //     },
        //     set(val: boolean) {
        //         _isActive = val;
        //         if (activeSubject) {
        //             activeSubject.next(val);
        //         }
        //     }
        // });

        onMounted(() => {
            // .pipe(
            //     takeUntil(destroy$)
            // )
            // activedSubscrition = activeSubject.pipe(
            //     filter((n: boolean) => {
            //         return n;
            //     }),
            // ).subscribe(v => {
            if (isActive.value) {
                // setTimeout(() => {
                const loadingBackdropRefValue = loadingBackdrop.value;
                loadingBackdropRefValue?.style?.setProperty('display', `block`);
                const loadingContainerElRefValue = loadingContainerEl.value;
                loadingContainerElRefValue?.style?.setProperty('left', '0');
                setPosition();
                loadingContainerElRefValue?.style?.removeProperty('visibility');
                loadingContainerElRefValue?.style?.removeProperty('left');
                // }, delay);
            }
            // });
        });

        // onUnmounted(() => {
        //     cleanup();
        // });

        // const cleanup = () => {
        //     destroy$.next(null);
        //     destroy$.complete();
        // };

        function close() {
            if (loadingBackdrop.value) {
                loadingBackdrop.value.remove();
            }
            if (loadingContainerEl.value) {
                loadingContainerEl.value.remove();
            }
            isActive.value = false;
            document.documentElement.removeAttribute('class');
            context.emit('closed', isActive);
        }

        function setPosition() {
            const containerWidth = loadingContainerEl.value?.clientWidth;
            const containerHeight = loadingContainerEl.value?.clientHeight;
            const loadingContainerElRefValue = loadingContainerEl.value;
            const loadingBackdropRefValue = loadingBackdrop.value;
            if (containerWidth && containerHeight) {
                loadingContainerElRefValue?.style?.setProperty('marginTop', -containerHeight / 2 + 'px');
                let ml = -containerWidth / 2 + 'px';
                if (parentContainer) {
                    if (parentContainer.clientWidth <= 200) {
                        ml = '-100px';
                    }
                }
                loadingContainerElRefValue?.style?.setProperty('marginLeft', ml);
            }
            const zindex = getFloatingLayerIndex();
            loadingBackdropRefValue?.style?.setProperty('zIndex', (zindex + 1).toString());
            loadingContainerElRefValue?.style?.setProperty('zIndex', (zindex + 1).toString());
        }
        /**
           * 获取页面中body下所有元素的zIndex, 并返回下个浮层的新zindex
           */
        function getFloatingLayerIndex(upperLayers = 1) {
            const selectors = [
                'body>.f-datagrid-settings-simple-host',
                'body>div',
                'body>farris-dialog>.farris-modal.show',
                'body>.farris-modal.show',
                'body>farris-filter-panel>.f-filter-panel-wrapper',
                'body .f-sidebar-show>.f-sidebar-main',
                'body>.popover.show',
                'body>filter-row-panel>.f-datagrid-filter-panel',
                'body>.f-section-maximize'
            ];

            const overlays = Array.from(document.body.querySelectorAll(selectors.join(','))).filter(n => n).map(n => {
                const { display, zIndex } = window.getComputedStyle(n);
                if (display === 'none') {
                    return 0;
                }
                return parseInt(zIndex, 10);
            }).filter(n => n);
            let maxZindex = Math.max(...overlays);
            if (maxZindex < 1040) {
                maxZindex = 1040;
            }
            return maxZindex + upperLayers;
        }

        const closeWhenClick = (event: MouseEvent) => {
            if (props.debug) {
                event.stopPropagation();
                close();
                // const loadingContainerElRefValue = loadingContainerEl.value;
                // loadingContainerElRefValue?.style?.removeProperty('visibility');
                // loadingContainerElRefValue?.style?.removeProperty('left');
            }
        };

        return () => {
            return (
                <div>
                    <div ref={loadingBackdrop} class="farris-loading-backdrop loading-wait" onClick={closeWhenClick}>
                    </div>
                    <div ref={loadingContainerEl} class="farris-loading" style="visibility: hidden">
                        <div class="ng-busy-default-wrapper">
                            <div class="ng-busy-default-sign" >
                                <div style={[
                                    { display: 'inline-block' },
                                    { margin: '4px' },
                                    { width: width + 'px' },
                                    { height: width + 'px' }
                                ]}
                                innerHTML={loadingStyleDom[type]}>
                                </div>
                                {props.showMessage && (
                                    <div class="ng-busy-default-text" style="margin-left:0;" innerHTML={props.message}>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            );
        };
    }
});
